package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //存放从begin，到end每天
        List<LocalDate> dateList=new ArrayList<>();

        //先存放第一天
        dateList.add(begin);

        //直到begin->end
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天营业额
        List<Double> turnoverList=new ArrayList<>();
        for(LocalDate date:dateList){
            //获取当天的最小时间和最大时间
            LocalDateTime beginTime= LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date,LocalTime.MAX);

            Map map= new HashMap();
            //设置最小时间，最大时间，和“已完成”状态
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            //查询当天营业额     营业额=当天的状态为”已完成“订单的价钱总和
            Double turnover=reportMapper.getDateTurnover(map);
            //如果当天没营业额会返回空，设置成0.00
            turnover=turnover==null?0.00:turnover;
            //添加营业额
            turnoverList.add(turnover);
        }

        //把每天以,形式分割  2025-12-1,2025-12-2,2025-12-3
        //把每天营业额以，形式分割 12.00,13.00,67.00
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户数量统计
     * 统计begin-end间的用户总数和每日新增用户数量
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserReport(LocalDate begin, LocalDate end) {
        //记录每日的列表
        List<LocalDate> dateList=new ArrayList<>();

        //添加每日数据
        dateList.add(begin);

        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //记录每日新增用户列表
        List<Integer> newUserList=new ArrayList<>();
        //记录每日用户总数
        List<Integer> allUserList=new ArrayList<>();

        //
        for (LocalDate date:dateList){
            //创建当前的最小时间和最大时间
            LocalDateTime dateBegin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime dateEnd = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap<>();
            map.put("dateEnd",dateEnd);

            //先计算date及之前总用户  date最大时间<create_time 的id总数
            allUserList.add(reportMapper.getUserReport(map));

            //计算每日新增用户  date最小时间<create_time and create_time<date最大时间 的id总数
            map.put("dateBegin",dateBegin);
            newUserList.add(reportMapper.getUserReport(map));
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(allUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单数量统计 每日订单、有效订单/ begin-end的总订单、有效订单、订单率=有效订单/总订单*100%
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderReport(LocalDate begin, LocalDate end) {
        //统计每日
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //每日总订单
        List<Integer> dateOrdersList=new ArrayList<>();
        //每日有效订单
        List<Integer> validOrdersList=new ArrayList<>();

        //总订单数
        Integer allDateOrders=0;
        //总有效订单数据量
        Integer allValidOrders=0;

        for (LocalDate date:dateList){
            //每日最小时间
            LocalDateTime dateBegin = LocalDateTime.of(date, LocalTime.MIN);
            //每日最大时间
            LocalDateTime dateEnd = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap<>();
            map.put("dateBegin",dateBegin);
            map.put("dateEnd",dateEnd);
            map.put("status",Orders.COMPLETED);//订单状态5
            //查询每日总订单数
            Integer dateOrder=reportMapper.getDateOrder(map);
            //添加到总订单列表内
            dateOrdersList.add(dateOrder);
            //累计总订单数
            allDateOrders+=dateOrder;

            //查询每日有效订单数
            Integer validOrder=reportMapper.getDateOrder(map);
            //添加到有效订单列表内
            validOrdersList.add(dateOrder);
            //累计总有效订单数
            allValidOrders+=validOrder;
        }
        //订单率
        Double orderCompletionRate=0.0;
        if (allDateOrders!=0){
            orderCompletionRate=allDateOrders.doubleValue()/allValidOrders;
        }

        //封装返回结果
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(dateOrdersList,","))
                .validOrderCountList(StringUtils.join(validOrdersList,","))
                .totalOrderCount(allDateOrders)
                .validOrderCount(allValidOrders)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计begin-end销量前10的数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getReportTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //获取前10的数据
        List<GoodsSalesDTO> top10Report=reportMapper.getTop10(beginTime,endTime);

        //把GoodsSalesDTO内的商品名称，和商品销量提取出来 并且拼接成 ---,---,---
        List<String> nameList=top10Report.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String names = StringUtils.join(nameList, ",");

        List<Integer> numberList=top10Report.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numbers=StringUtils.join(numberList,",");

        //封装返回对象数据
        return SalesTop10ReportVO.builder()
                .nameList(names)
                .numberList(numbers)
                .build();

    }

    /**
     * 导出近30天内的数据统计 Excel表
     * @param response
     */
    public void getExport(HttpServletResponse response) {
        //1.查询数据库30天内（不包含今天）的营业相关数据

        //30天前---昨天
        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end=LocalDate.now().minusDays(1);

        //获取30天前的最小时间和昨天的最大时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //获取相关数据
        BusinessDataVO dataVO = workspaceService.getBusinessData(beginTime, endTime);

        //2.通过POI将数据写入Excel表

        //获取表
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //获取excel
            XSSFWorkbook excel=new XSSFWorkbook(in);

            //获取sheet页
            XSSFSheet sheet=excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+begin+"至"+end);

            //获得第四行
            XSSFRow row=sheet.getRow(3);
            //添加营业额
            row.getCell(2).setCellValue(dataVO.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
            //新增用户数
            row.getCell(6).setCellValue(dataVO.getNewUsers());

            //获取第五行
            row=sheet.getRow(4);
            //有效订单数
            row.getCell(2).setCellValue(dataVO.getValidOrderCount());
            //平均客单价
            row.getCell(4).setCellValue(dataVO.getUnitPrice());


            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date=begin.plusDays(i);
                //查询当前data的营业数据
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获取某行
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            }

            //3.通过输出流讲Excel文件下载到客户带
            ServletOutputStream out=response.getOutputStream();
            excel.write(out);

        } catch (IOException e) {
            throw new RuntimeException("导出失败，请重试");
        }
    }
}
